<?php 
namespace app\admin\controller;

use app\common\controller\Adminbase;
use think\Db;
use app\admin\model\Product as ProductModel;
use app\admin\model\Danwei as DanweiModel;
use app\admin\model\Ruku as RuKuModel;
use app\admin\model\AdminUser;
//入库单控制器
class Warehousing extends Adminbase
{
    public function index()
    {
        if ($this->request->isAjax()) {
            $page = $this->request->param('page');
            $limit = $this->request->param('limit');
            if($this->request->param('filter')){
                $filter = $this->request->param('filter');
                $filter = json_decode($filter,true);
                foreach($filter as $k=>$row){
                    $where[] = [$k,'like','%'.trim($row).'%'];
                }
            }
            $offset = ($page - 1)*$limit;
            $result = RuKuModel::where('deleted',0)->where($where)->limit($offset,$limit)->select();
            $type = [
                '1'=>'普通入库',
                '2'=>'采购入库',
                '3'=>'成品入库',
                '4'=>'调拨入库',
                '5'=>'销售退货入库',
                '6'=>'其它入库',
            ];
            foreach($result as $k=>$row){
                $result[$k]['admin'] = AdminUser::getAdmin($row['admin_id'],'nickname');
                $result[$k]['type_msg'] = $type[$row['type']];
            }
            $count = RuKuModel::where('deleted',0)->where($where)->count();
            $result = array("code" => 0, 'count'=>$count,"data" => $result);
            return json($result);
        }
        return $this->fetch();
    }

    public function add()
    {
        //产品列表
        $productList = ProductModel::field('id,title,nums,stock')->select();
        // dg($productList);
        $this->assign('productList',$productList);
        return $this->fetch();
    }
    public function edit()
    {
        $id = $this->request->param('id');
        //产品列表
        $productList = ProductModel::field('id,title,nums,stock')->select();
        // dg($productList);
        $this->assign('productList',$productList);
        //入单详情
        $ruku = RuKuModel::find($id);
        //入库列表
        $rkList = [];
        $list = Db::name('gd_stock_follow')->where(['ruku_id'=>$id,'type'=>1,'deleted'=>0])->select();
        foreach($list as $k=>$row){
            $paroduct = ProductModel::field('id,nums,title,guige,stock,danwei_id')->find($row['product_id'])->toArray();
            $rkList[$k]['count'] = $row['nums'];
            $rkList[$k]['danwei'] = DanweiModel::field('title')->find($product['danwei_id'])->title;
            $rkList[$k]['guige'] = $paroduct['guige'];
            $rkList[$k]['title'] = $paroduct['title'];
            $rkList[$k]['stock'] = $paroduct['stock'];
            $rkList[$k]['nums'] = $paroduct['nums'];
            $rkList[$k]['id'] = $paroduct['id'];
        }
        $this->assign('ruku',$ruku);
        $this->assign('rkList',$rkList);
        return $this->fetch();
    }

    public function getProDetail()
    {
        $id = $this->request->param('id');
        $product = ProductModel::field('id,nums,title,guige,stock,danwei_id')->find($id);
        $danwei = DanweiModel::field('title')->find($product['danwei_id']);
        $product['danwei'] = $danwei['title'];
        return json(['code'=>1,'product'=>$product]);
    }

    public function editPost()
    {
        $data = $this->request->param();
        if(empty($data['pid'])){
            $this->error('必须添加一个产品');
        }
        // dg($data);
        // exit();
        if(!isset($data['id'])){  //新增入库
            if(isset($data['pid']) && !empty($data['pid']) && !empty($data['counts'])){
                if (count($data['pid']) != count(array_unique($data['pid']))) {   
                    $this->error('产品编号不得重复');
                } 
                Db::startTrans();
                try{
                    //添加进入库表
                    $rukuId = RuKuModel::insertGetId([
                        'type'=>$data['type'],
                        'number'=>'IN'.date('YmdHis'),
                        'bz'=>$data['bz'],
                        'create_time'=>$data['create_time'],
                        'addtime'=>date('Y-m-d H:i:s'),
                        'admin_id'=>session('admin_user_auth')['uid']
                    ]);
                    foreach($data['pid'] as $k=>$id){
                        //添加进明细表
                        Db::name('gd_stock_follow')->insert([
                            'product_id'=>$id,
                            'ruku_id'=>$rukuId,
                            'nums'=>$data['counts'][$k],
                            'type'=>1,
                            'addtime'=>date('Y-m-d H:i:s')
                        ]);
                        //更改产品表的库存
                        $stock = Db::name('gd_product')->where('id',$id)->value('stock');
                        Db::name('gd_product')->where('id',$id)->update([
                            'stock'=>(int)$stock + $data['counts'][$k]
                        ]);
                    }
                    Db::commit();
                }catch(\Exception $e){
                    Db::rollback();
                    $this->error('添加失败');
                }
                $this->success('入库成功');
            }
        }else{  //编辑修改
            if(isset($data['pid']) && !empty($data['pid']) && !empty($data['counts'])){
                if (count($data['pid']) != count(array_unique($data['pid']))) {   
                    $this->error('产品编号不得重复');
                } 
                $rukuId = $data['id'];
                Db::startTrans();
                try{
                    //修改入库表
                    RuKuModel::where('id',$rukuId)->update([
                        'type'=>$data['type'],
                        'number'=>'IN'.date('YmdHis'),
                        'bz'=>$data['bz'],
                        'mdtime'=>date('Y-m-d H:i:s'),
                    ]);
                    if(!empty($data['deletedIds'])){  //删除的订单
                        foreach($data['deletedIds'] as $id){
                            $follow = Db::name('gd_stock_follow')->where(['ruku_id'=>$rukuId,'product_id'=>$id,'type'=>1,'deleted'=>0])->find();
                            Db::name('gd_stock_follow')->where(['ruku_id'=>$rukuId,'product_id'=>$id,'type'=>1,'deleted'=>0])->update([
                                'deleted'=>1,
                                'mdtime'=>date('Y-m-d H:i:s'),
                            ]);
                            //更改库存
                            $stock = Db::name('gd_product')->where('id',$id)->value('stock');
                            Db::name('gd_product')->where('id',$id)->update([
                                'stock'=>(int)$stock - $follow['nums']
                            ]);
                        }
                    }
                    //修改流水表
                    foreach($data['pid'] as $k=>$id){
                        $follow = Db::name('gd_stock_follow')->where(['ruku_id'=>$rukuId,'product_id'=>$id,'type'=>1,'deleted'=>0])->find();
                        if(!empty($follow) && (int)$follow['nums'] != (int)$data['counts'][$k]){  //已存在该流水,并且数量有变化
                            Db::name('gd_stock_follow')->where('id',$follow['id'])->update([
                                'nums'=>$data['counts'][$k],
                                'mdtime'=>date('Y-m-d H:i:s'),
                            ]);
                            $stock = Db::name('gd_product')->where('id',$id)->value('stock');
                            if((int)$data['counts'][$k] >= (int)$follow['nums']){ //修改的大于之前的
                                //更改产品表的库存
                                Db::name('gd_product')->where('id',$id)->update([
                                    'stock'=>(int)$stock + ((int)$data['counts'][$k] - (int)$follow['nums'])
                                ]);
                            }else{
                                //更改产品表的库存
                                Db::name('gd_product')->where('id',$id)->update([
                                    'stock'=>(int)$stock - ((int)$follow['nums'] - (int)$data['counts'][$k])
                                ]);
                            }
                        }elseif(empty($follow)){
                            //添加进明细表
                            Db::name('gd_stock_follow')->insert([
                                'product_id'=>$id,
                                'ruku_id'=>$rukuId,
                                'nums'=>$data['counts'][$k],
                                'type'=>1,
                                'addtime'=>date('Y-m-d H:i:s')
                            ]);
                            //更改产品表的库存
                            $stock = Db::name('gd_product')->where('id',$id)->value('stock');
                            Db::name('gd_product')->where('id',$id)->update([
                                'stock'=>(int)$stock + $data['counts'][$k]
                            ]);
                        }
                    }
                    Db::commit();
                }catch(\Exception $e){
                    Db::rollback();
                    $this->error('添加失败');
                }
                $this->success('入库成功');
            }
        }
    }

    public function delete()
    {
        $data = $this->request->param();
        Db::startTrans();
        try{
            RuKuModel::where('id',$data['id'])->update(['deleted'=>1]);
            $followList = Db::name('gd_stock_follow')->where(['ruku_id'=>$data['id'],'type'=>1,'deleted'=>0])->select();
            Db::name('gd_stock_follow')->where(['ruku_id'=>$data['id'],'type'=>1])->update([
                'deleted'=>1,
                'mdtime'=>date('Y-m-d H:i:s'),
            ]);
            foreach($followList as $row){
                // //更改库存
                $stock = Db::name('gd_product')->where('id',$row['product_id'])->value('stock');
                Db::name('gd_product')->where('id',$row['product_id'])->update([
                    'stock'=>(int)$stock - $row['nums']
                ]);
            }
            Db::commit();
        }catch(\Exception $e){
            dg($e);
            Db::rollback();
            $this->error('删除失败');
        }
        $this->success('删除成功',url('index'));
    }
}

